package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.adapter.ModelListAdapter;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.MemberInfoApi;
import com.moyun.modelclass.http.api.MyModelApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

/**
 * 作者：Meteor
 * tip：我的模型
 */
public class MyModelActivity extends BaseActivity implements ModelListAdapter.OnItemSelectedChangedListener {
    private RelativeLayout llMyModelTop;
    private ImageView ivMyModelBack;
    private TextView tvMyModelUpload;
    private ProgressBar progressMyModel;
    private TextView progressMyModelOne;
    private TextView progressMyModelTwo;
    private TextView tvMyModelAddSpace;
    private EditText etMyModelContent;
    private TextView tvMyModelButton;
    private SmartRefreshLayout myModelRefresh;
    private RecyclerView myModelRecycler;

    private ModelListAdapter modelListAdapter = new ModelListAdapter();
    private String mLastId = "";

    public static void start(Context context) {
        Intent starter = new Intent(context, MyModelActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_my_model;
    }

    @Override
    protected void assignViews() {
        llMyModelTop = (RelativeLayout) findViewById(R.id.ll_my_model_top);
        ivMyModelBack = (ImageView) findViewById(R.id.iv_my_model_back);
        tvMyModelUpload = (TextView) findViewById(R.id.tv_my_model_upload);
        progressMyModel = (ProgressBar) findViewById(R.id.progress_my_model);
        progressMyModelOne = (TextView) findViewById(R.id.progress_my_model_one);
        progressMyModelTwo = (TextView) findViewById(R.id.progress_my_model_two);
        tvMyModelAddSpace = (TextView) findViewById(R.id.tv_my_model_add_space);
        etMyModelContent = (EditText) findViewById(R.id.et_my_model_content);
        tvMyModelButton = (TextView) findViewById(R.id.tv_my_model_button);
        myModelRefresh = (SmartRefreshLayout) findViewById(R.id.my_model_refresh);
        myModelRecycler = (RecyclerView) findViewById(R.id.my_model_recycler);


        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
        myModelRecycler.setLayoutManager(layoutManager);
        modelListAdapter.setOnItemSelectedChangedListener(this);
        myModelRecycler.setAdapter(modelListAdapter);

        StatusBarUtil.setPaddingSmart(this, llMyModelTop);
    }


    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivMyModelBack, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ClickUtils.applySingleDebouncing(tvMyModelUpload, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditModelActivity.start(MyModelActivity.this, "");
            }
        });

        ClickUtils.applySingleDebouncing(tvMyModelAddSpace, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CommonConfiguration.isLogin(kv)) {
                    VipActivity.start(MyModelActivity.this);
                } else {
//                    ToastUtils.showShort(getString(R.string.http_token_error));
                    LoginVerificationCodeActivity.start(MyModelActivity.this);
                }
            }
        });

        myModelRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mLastId = "";
                modelListData(true, "");
            }
        });
        myModelRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                modelListData(false, "");
            }
        });

        ClickUtils.applySingleDebouncing(tvMyModelButton, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String searchResult = etMyModelContent.getText().toString().trim();
                KeyboardUtils.hideSoftInput(etMyModelContent);
                etMyModelContent.clearFocus();
                modelListData(true, searchResult);
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initMemberInfo();
        modelListData(true, "");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        modelListData(true, "");
    }

    private void modelListData(boolean isRefresh, String searchString) {
        mLastId = isRefresh ? "" : mLastId;
        EasyHttp.post(this)
                .api(new MyModelApi().setUserId(CommonConfiguration.getUseId(kv)).setLastId(mLastId).setSearch(searchString).setPageSize(CommonConfiguration.page))
                .request(new HttpCallback<HttpData<MyModelApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<MyModelApi.Bean> result) {
                        myModelRefresh.finishRefresh();
                        myModelRefresh.finishLoadMore();
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            mLastId = result.getData().getList().get(result.getData().getList().size() - 1).getId();
                            Log.e("mLastId==>", mLastId);
                            if (isRefresh) {
                                modelListAdapter.setList(result.getData().getList());
                            } else {
                                modelListAdapter.addData(result.getData().getList());
                            }
                        } else {
                            if (isRefresh) {
                                modelListAdapter.setList(new ArrayList<>());
                                modelListAdapter.setEmptyView(R.layout.empty_view_layout);
                            }
                        }
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    private void initMemberInfo() {
        EasyHttp.post(this)
                .api(new MemberInfoApi())
                .request(new HttpCallback<HttpData<MemberInfoApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<MemberInfoApi.Bean> result) {
                        if (result.getData() != null) {
                            long useSpace = result.getData().getUseSpace() / (1024 * 1024);
                            long totalSpace = result.getData().getTotalSpace() / (1024 * 1024);
                            progressMyModel.setProgress((int) (useSpace * 100 / totalSpace));
                            progressMyModelOne.setText(useSpace + "M");
                            progressMyModelTwo.setText(totalSpace + "M");
                        }
                    }
                });
    }

    @Override
    public void details(String modelId) {
        ModelDetailsActivity.start(this, modelId, true);
    }
}
